package influencer

import (
	"fmt"
	"gorm.io/gorm"
	"h_rpcx/internet/mode/everydayDatas"
	"h_rpcx/internet/mode/influencersInfo"
	"h_rpcx/until"
	"time"
)

type Influencer struct {
	Id            int32                           `json:"id" gorm:"column:id;comment:'id'"`
	PlatformId    int32                           `json:"platform_id" gorm:"column:platform_id;comment:'平台ID'"`
	Nickname      string                          `json:"nickname" gorm:"column:nickname;comment:'昵称'"`
	Avatar        string                          `json:"avatar" gorm:"column:avatar;comment:'头像'"`
	UserId        int32                           `json:"user_id" gorm:"column:user_id;comment:'经纪人(后台用户)ID'"`
	IsMcn         int8                            `json:"is_mcn" gorm:"column:is_mcn;comment:'是否mcn  1 直播  2 达人  3 直播和达人'"`
	Signing       int8                            `json:"signing" gorm:"column:signing;comment:'签约  0否  1是'"`
	SigningTime   time.Time                       `json:"signing_time" gorm:"column:signing_time;comment:'签约时间'"`
	Bonus         string                          `json:"bonus" gorm:"column:bonus;comment:'分成比例 百分比直播'"`
	AdBonus       string                          `json:"ad_bonus" gorm:"column:ad_bonus;comment:'分成比例 百分比 MCN'"`
	ShopBonus     string                          `json:"shop_bonus" gorm:"column:shop_bonus;comment:'分成比例 百分比 电商'"`
	Comment       string                          `json:"comment" gorm:"column:comment;comment:'备注信息'"`
	JoinTime      time.Time                       `json:"join_time" gorm:"column:join_time;comment:'入会时间'"`
	Distributions int8                            `json:"distributions" gorm:"column:distributions;comment:'是否分配(1未分配 2 已分配)'"`
	Source        int8                            `json:"source" gorm:"column:source;comment:'主播类型(  1 自营  2 合作)'"`
	Partners      string                          `json:"partners" gorm:"column:partners;comment:'合作机构'"`
	PartnerId     string                          `json:"partner_id" gorm:"column:partner_id;comment:'机构ID'"`
	IsRecommend   string                          `json:"is_recommend" gorm:"column:is_recommend;comment:'2广告商单  3直播业务  4电商业务'"`
	Ratio         string                          `json:"ratio" gorm:"column:ratio;comment:'奖金比例'"`
	Level         string                          `json:"level" gorm:"column:level;comment:'等级'"`
	PartnerMcnId  string                          `json:"partner_mcn_id" gorm:"column:partner_mcn_id;comment:'mcn机构ID'"`
	IsJoin        int8                            `json:"is_join" gorm:"column:is_join;comment:'首次入会默认为1 ，二次入会为2'"`
	LiveOperate   int32                           `json:"live_operate" gorm:"column:live_operate;comment:'直播运营ID'"`
	AdOperate     int8                            `json:"ad_operate" gorm:"column:ad_operate;comment:'广告运营ID'"`
	ShopOperate   int8                            `json:"shop_operate" gorm:"column:shop_operate;comment:'电商运营ID'"`
	CreatedAt     time.Time                       `json:"created_at" gorm:"column:created_at;comment:'created_at'"`
	UpdatedAt     time.Time                       `json:"updated_at" gorm:"column:updated_at;comment:'updated_at'"`
	DeletedAt     time.Time                       `json:"deleted_at" gorm:"column:deleted_at;comment:'deleted_at'"`
	Info          influencersInfo.InfluencersInfo `json:"info" gorm:"foreignKey:id;references:influencers_id"`
	Water         *Waters                         `json:"water" gorm:"-"`
}

type Waters struct {
	Yesterday         int   `json:"yesterday"`
	ThisMonth         int   `json:"this_month"`
	Duration          int   `json:"duration"`
	ThisMonthDuration int32 `json:"thi_month_duration"`
}

func NewInfluencer() *Influencer {
	return &Influencer{}
}

func (*Influencer) TableName() string {
	return "hx_influencers"
}

//经济艺人
func (i *Influencer) EconomicActor(db *gorm.DB, uid int32) (map[string]interface{}, error) {
	m := make(map[string]interface{}, 8)
	var broker_count int64
	var operation_count int64
	var this_month_add int64
	var last_month_add int64
	var this_month_sign int64
	var last_month_sign int64
	err := db.Model(&Influencer{}).Where("user_id != ?", uid).Where("live_operate = ? or ad_operate = ? or shop_operate = ?", uid, uid, uid).
		Where("deleted_at is null").Select("id").Count(&operation_count).Error
	err = db.Model(&Influencer{}).Where("user_id = ?", uid).Where("deleted_at is null").Count(&broker_count).Error
	ti := until.FirstAndLast(time.Now())
	//这个月1号和当前的时间
	now := until.ThisMonthFirstToNow(time.Now())
	err = db.Model(&Influencer{}).Where("user_id=?", uid).Where("deleted_at is null").
		Where("join_time > ? and join_time < ?", now["first_day"], now["last_day"]).Select("id").Count(&this_month_add).Error
	err = db.Model(&Influencer{}).Where("user_id=?", uid).
		Where("deleted_at is null").Where("join_time > ? and join_time < ?", ti["first_day"], ti["last_day"]).Select("id").Count(&last_month_add).Error
	err = db.Model(&Influencer{}).Where("user_id=?", uid).
		Where("deleted_at is null").Where("signing_time > ? and signing_time < ?", now["first_day"], now["last_day"]).Select("id").Count(&this_month_sign).Error
	err = db.Model(&Influencer{}).Where("user_id=?", uid).
		Where("deleted_at is null").Where("signing_time > ? and signing_time < ?", ti["first_day"], ti["last_day"]).Select("id").Count(&last_month_sign).Error
	m["broker_count"] = broker_count
	m["operation_count"] = operation_count
	m["this_month_add"] = this_month_add
	m["last_month_add"] = last_month_add
	m["this_month_sign"] = this_month_sign
	m["last_month_sign"] = last_month_sign
	if err != nil {
		return nil, err
	}
	return m, nil
}

//列表
func (i *Influencer) List(db *gorm.DB, key string, pageSize int32, uid int32) ([]*Influencer, error) {
	fmt.Println(key)
	influencers := make([]*Influencer, pageSize)
	query := db.Model(&Influencer{}).Debug()
	if key != "" {
		query = query.Where("nickname like ? or EXISTS("+
			"select * from hx_influencers_info where hx_influencers.id = hx_influencers_info.influencers_id and (short_id like ? or unique_id like ?) and hx_influencers_info.deleted_at is null"+
			")",
			"%"+key+"%", "%"+key+"%", "%"+key+"%")
	}
	query.Preload("Info", func(db *gorm.DB) *gorm.DB {
		in := db.Select("influencers_id", "short_id")
		return in
	}).Where("user_id = ? or live_operate = ? or ad_operate = ? or shop_operate = ?", uid, uid, uid, uid).Limit(int(pageSize)).Find(&influencers)
	//获取昨天的时间
	yesterday := until.YesterdayStartAndEnd(time.Now())
	//获取当月1号
	month := until.ThisMonthFirstToNow(time.Now())
	every := everydayDatas.NewEverydayDatas()
	for k, v := range influencers {
		yesterdaySummary, err := every.SummaryData(db, yesterday["start"], yesterday["end"], v.Id)
		fmt.Println(yesterdaySummary)
		data, err := every.SummaryData(db, month["first_day"], month["last_day"], v.Id)
		if err != nil {
			panic(err.Error())
		}
		influencers[k].Water = &Waters{
			Yesterday:         yesterdaySummary["yesterday"].(int),
			ThisMonth:         data["this_month"].(int),
			Duration:          yesterdaySummary["duration"].(int),
			ThisMonthDuration: data["thi_month_duration"].(int32),
		}
	}
	return influencers, nil
}
